/**
 *
 * @author ilya portnyagin iportnyagin@gmail.com
 * decision from BalusC for p:graphicImage
 */
package ru.portnyagin.helpdeskru.controller;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Serializable;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import ru.portnyagin.helpdeskru.model.FileHD;


@ManagedBean(name = "imageAsStreamContent")
@ApplicationScoped
public class ImageAsStreamContent implements Serializable{
    
    private FileHD currentImage;

    public ImageAsStreamContent() {
    }
    
    public FileHD getCurrentImage() {
        return currentImage;
    }
  
    public void setCurrentImage(FileHD currentImage) {
        this.currentImage = currentImage;
    }

    public StreamedContent getCurrentImageAsStreamedContent() {
        
        if(currentImage == null) 
            return null;
        
        FacesContext context = FacesContext.getCurrentInstance();

        if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
            return new DefaultStreamedContent();
        }
        else {
            InputStream is = new ByteArrayInputStream(currentImage.getContent());
            StreamedContent sc = new DefaultStreamedContent(is, "image/jpg", currentImage.getName());
            return sc;
        }
    }    
    
}
